package cn.hdax.test1;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

public class WordCountTool implements Tool {
    public static class WordCountMapper extends Mapper<LongWritable,Text,Text,LongWritable>
    {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            System.out.println(key.get() + " -- " + value.toString());

            String[] words = value.toString().split(" ") ;
            for(String s : words){
                context.write(new Text(s),new LongWritable(1));
            }

        }
    }

    public static class WordCountReduce extends Reducer<Text,LongWritable,Text,LongWritable>
    {
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0 ;
            for(LongWritable v :values){
                sum = sum + v.get() ;
            }

            context.write(key,new LongWritable(sum));
        }
    }


    private Configuration configuration ;


    @Override
    public int run(String[] args) throws Exception {
        Configuration configuration = this.getConf() ;
        //
        Job job = Job.getInstance(configuration,"wordcount") ;
        job.setJarByClass(WordCount.class);
        //
        Path pathin = new Path("/a1.txt") ;
        job.setMapperClass(WordCountMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);
        FileInputFormat.setInputPaths(job,pathin);


        //
        Path pathout = new Path("/t176/out") ;

        FileSystem fileSystem = FileSystem.get(configuration) ;
        if(fileSystem.exists(pathout)){
            fileSystem.delete(pathout,true) ;
        }

        job.setReducerClass(WordCountReduce.class);
        job.setOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);
        FileOutputFormat.setOutputPath(job,pathout);

        return  job.waitForCompletion(true) ? 0 : 1 ;
    }

    @Override
    public void setConf(Configuration conf) {
        configuration = new Configuration() ;
    }

    @Override
    public Configuration getConf() {
        return this.configuration;
    }


    public static void main(String[] args) throws Exception{
        int exitCode = ToolRunner.run(new Configuration(),new WordCountTool(), args);
        System.exit(exitCode);
    }
}
